const cheerio = require("cheerio");
const fetch = require("node-fetch");

const sentence = async (ctx) => {
  const { redis } = ctx
  const { word } = ctx.request.query;
  if (!word) ctx.throw(400, ".word required");
  const cache = await redis.get(word)
  if (cache) {
    ctx.response.body = JSON.parse(cache)
    return
  }
  const url = `https://dictionary.cambridge.org/zhs/%E8%AF%8D%E5%85%B8/%E8%8B%B1%E8%AF%AD-%E6%B1%89%E8%AF%AD-%E7%AE%80%E4%BD%93/${word}`
  const html = await fetch(url).then((res) => res.text());
  const $ = cheerio.load(html);
  const more = $("#dataset-example .deg")
    .toArray()
    .map(function (it) {
      return $(it).text().trim();
    });

  const details = $('.sense-body .ddef_block').toArray().map(function (it) {
    const meaning = $(it).find('.ddef_d').text().trim()
    const meaningTrans = $(it).find('.ddef_b > .trans').text().trim()
    const examples = $(it).find('.ddef_b .dexamp').toArray().map(example => {
      return {
        sentence: $(example).find('.deg').text().trim(),
        trans: $(example).find('.dtrans').text().trim()
      }
    })
    return {
      meaning,
      meaningTrans,
      examples,
    }
  });
  const res = { more, details };
  redis.set(word, JSON.stringify(res))
  ctx.response.body = res
};

module.exports = sentence;
